package net.maxwoods.nimble.springmvc.config;

import net.maxwoods.nimble.springmvc.annotation.MyAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.lang.annotation.Annotation;
import java.util.HashMap;

@Component
public class BeanProcessor implements BeanPostProcessor {

    private static final Logger logger = LoggerFactory.getLogger(BeanProcessor.class);

    @Autowired
    private ServletContext servletContext;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        logger.info("======初始化开始:{}", bean.getClass().getName());
        return bean;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        logger.info("======初始化完成:{}", bean.getClass().getName());
        Annotation annotation = bean.getClass().getAnnotation(MyAnnotation.class);
        if (annotation != null) {
            logger.info("匹配到注解服务：{}", beanName);
            HashMap pppcServices = (HashMap) servletContext.getAttribute("PPPCServices");
            pppcServices.put(bean.getClass(), bean);
            logger.info("已检测到服务:{}", pppcServices.size());
        }
        return bean;
    }
}
